#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import logging

import openai

from utils.config import Config


class GPTUtil:

    def __init__(self) -> None:
        config = Config()
        openai.api_key = config.OPEN_AI["api_key"]
        # 自己搭建或第三方代理的接口
        openai.api_base = config.OPEN_AI["api_url"]
        self.conversation_list = {}
        self.log = logging.getLogger(__name__)

    def get_answer(self, question: str, wxid: str) -> str:
        # wxid或者roomid,个人时为微信id，群消息时为群id
        self.updateMessage(wxid, question, "user")
        rsp = self.getChatGPTAnswer(self.conversation_list[wxid])
        self.updateMessage(wxid, rsp, "assistant")
        return rsp

    def getChatGPTAnswer(self, question):
        try:
            ret = openai.ChatCompletion.create(
                #gpt-4-1106-preview
                model="gpt-3.5-turbo",
                messages=question,
                temperature=0.2
            )
            rsp = ret["choices"][0]["message"]["content"]
        except openai.error.AuthenticationError as e3:
            rsp = "OpenAI API 认证失败，请检查 API 密钥是否正确"
        except openai.error.APIConnectionError as e2:
            rsp = "无法连接到 OpenAI API，请检查网络连接"
        except openai.error.APIError as e1:
            rsp = "OpenAI API 返回了错误：" + str(e1)
        except Exception as e0:
            rsp = "发生未知错误：" + str(e0)
        return rsp

    def updateMessage(self, wxid: str, question: str, role: str) -> None:
        # 初始化聊天记录,组装系统信息
        if wxid not in self.conversation_list.keys():
            question_ = [
                {"role": "system", "content": ""}
            ]
            self.conversation_list[wxid] = question_

        # 将当前问题存储到上下文中
        content_question_ = {"role": role, "content": question}
        self.conversation_list[wxid].append(content_question_)
        # 只存储10条记录，超过滚动清除
        i = len(self.conversation_list[wxid])
        if i > 10:
            self.log.info("滚动清除微信记录：" + wxid)
            # 删除多余的记录，倒着删，且跳过第一个的系统消息
            del self.conversation_list[wxid][1]
